import axios, { AxiosResponse, Method } from "axios";
import useUser from "../hook/user";
import { ElMessage} from 'element-plus'
import { useRouter } from 'vue-router';

const router = useRouter()

const baseUrl: string = (
	(import.meta.env.VITE_API_BASE_URL as string) ? import.meta.env.VITE_API_BASE_URL : "/"
) as string;

//提供一个请求包。path是相对当前请求所有的前缀
export default function useRequet(para: RequestInitPara): Request {
	const user = useUser();
	const path = baseUrl + (para.path ? para.path : "");
	

	const sendRequest = (requestPara: RequestPara) => {
		const url = path + requestPara.address;
		console.debug("请求的路径：",path,requestPara.address,url);

		const headers: any = {
			"Content-Type": "application/json",
		};

		if(user.getToken()){
			headers.Token = user.getToken()
			// headers.Token = '123'
		}

		let params = {};
		if (requestPara.method?.toUpperCase() === "GET") {
			params = {
				url: url,
				method: "GET",
				headers: headers,
				params: requestPara.params,
			};
		} else {
			params = {
				url: url,
				method: requestPara.method ? requestPara.method : "POST",
				headers:headers,
				data: requestPara.params,
			};
		}

		axios.request(params)
			.then((response) => {
				
				if (response.status >= 200 ) {
					if (response.data.code === 0) {
						user.setToken(response.headers.token);
						return requestPara.success ? requestPara.success(response.data) : response;
						
					} else if(response.data.code === 305 || response.data.code === 307 || response.data.code === 309 || response.data.code === 310) {
						ElMessage.error('身份验证异常，重新登录')
						
						window.localStorage.clear()
						
						router.go(0)
						
						return requestPara.success ? requestPara.success(response.data) : response;

						
					} else {
						return requestPara.fail ? requestPara.fail(response.data) : response;
					}
				} else {
					if (requestPara.error) {
						requestPara.error(response);
					} else {
						console.error("发送请求回复异常。。请求值:" + requestPara + "回复值：" + response);
					}
				}
			})
			.catch((error) => {
					console.error("网络传送出现异常。", error);
			});


	};

	let request = {
		sendRequest: sendRequest
	};

	return request;
}


export declare interface Request {
	sendRequest: (requestPara: RequestPara) => any;
}

export declare interface RespData {
	code?: number;
	data: any;
	msg?: string;
}

export declare interface RequestInitPara {
	path?: string;
}

export declare interface RequestPara {
	address: string;
	params?: any;
	method?: Method;
	success?: (resp: RespData) => void;
	fail?: (data: RespData) => void;
	error?: (data: AxiosResponse<any>) => void;
}

